<template>
  <div class="flex items-center h-full overflow-hidden">
    <AMapComp v-model:value="polygon" :rightActions="rightActions" class="flex-grow h-full" :polygons="polygons"
      :markers="markers" edit="polygon" search searchPosition="inside" @change="handleChange" :showPanel="showPanel"
      ref="amapRef" />
    <div class="absolute bottom-0 left-0 right-0 flex items-center p-4 space-x-4 text-sm bg-white/40">
      <div v-for="{ extData, index } in polygons" :key="index" class="p-2 bg-white rounded-sm"
        @click="toTarget(extData)">
        <div>{{ extData.name }}</div>
      </div>
      <div v-if="polygons.length == 0" class="p-2 bg-white rounded-sm">
        暂无地块，在地图中搜索地址，右键开始创建地块
      </div>
    </div>
    <div v-auth="'system:tenant:add'" @click="reflushRegion"
      class="reflesh absolute bottom-20 right-10 flex items-center space-x-4 text-sm bg-white"
      style="color: #1890ff; border-radius: 30px;cursor: pointer; padding: 10px 20px;">重新加载地块</div>
    <div class="dkgl_an" @click="show_djgl">
      <div class="anicon"></div>
    </div>
    <div class="relative flex-shrink-0 w-84 h-full dkgl_xx" :class="showDetail ? 'show' : 'yinc'">
      <div class="sc_an" @click="show_djgl">
        <div class="anicon_s"></div>
      </div>
      <div class="absolute inset-0 overflow-y-auto bg-whtie">
        <MenuOutlined class="absolute z-20 text-lg cursor-pointer top-4 right-4" @click="baseVisible = true" />
        <div class="p-3 bg-white">
          <!--          // 显示一部分，然后移动上去显示多的 todo-->
          <a-descriptions :column="1" title="基地信息" bordered class="custom-table-layout">
            <a-descriptions-item label="基地名称">
              <a-typography-text :style="{ width: '200px' }" :ellipsis="{ tooltip: true }">
                <a-tooltip :title="base.name">
                  <div class="overflow-text">{{ base.name }}</div>
                </a-tooltip>
              </a-typography-text>
            </a-descriptions-item>
            <a-descriptions-item label="基地地址">
              <a-typography-text :style="{ width: '200px' }" :ellipsis="{ tooltip: base.name }">
                <a-tooltip :title="base.poi">
                  <div class="overflow-text">{{ base.poi }}</div>
                </a-tooltip>
              </a-typography-text>
            </a-descriptions-item>
            <a-descriptions-item label="基地分类">
              <a-typography-text :style="{ width: '200px' }" :ellipsis="{ tooltip: true }">
                <a-tooltip :title="base.classification_dictText">
                  <div class="overflow-text">{{ base.classification_dictText }}</div>
                </a-tooltip>
              </a-typography-text>
            </a-descriptions-item>
            <a-descriptions-item label="环境信息">
              <a-typography-text :style="{ width: '200px' }" :ellipsis="{ tooltip: true }">
                <a-tooltip :title="base.environment">
                  <div class="overflow-text">{{ base.environment }}</div>
                </a-tooltip>
              </a-typography-text>
            </a-descriptions-item>
          </a-descriptions>
          <a-divider></a-divider>
          <TPlotModal v-model="polt" v-show="selected" :allowEdit="allowEdit" @changeColor="changeColor">
          </TPlotModal>
        </div>
      </div>
    </div>
    <a-drawer title="基地" v-model:open="baseVisible">
      <div v-for="(item, index) in bases" :key="index" class="flex items-center p-2 mb-4 text-sm border "
        :class="{ 'border-blue-500': currentBase == index }" @click="currentBase = index, baseVisible = false">
        <img :src="item.picture ? item.picture.split(',')[0] : ''"
          class="flex-shrink-0 object-contain mr-2 w-14 h-14" />
        <div class="flex-grow">
          <div>{{ item.name }}</div>
          <div class="mt-1 text-xs text-gray-500">{{ item.poi }}</div>
        </div>
      </div>
    </a-drawer>
    <a-modal v-model:open="selectColor" title="更改地块颜色" @ok="handleOk">
      <a-form :model="colors" :label-col="{ span: 6 }" :wrapper-col="{ span: 15 }">
        <a-form-item label="填充色">
          <a-input v-model:value="colors.fillColor" type="color" />
        </a-form-item>
        <a-form-item label="邊框色">
          <a-input v-model:value="colors.strokeColor" type="color" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang='ts'>
import { MenuOutlined } from '@ant-design/icons-vue';
import { watch, ref, computed, toRaw } from 'vue';
import AMapComp from '/@/components/AMap/AMap.vue'
import { list, changeStatus, reflushPlot } from './TPlot.api';
import { list as BaseList } from '../home/TBase.api';
import TPlotModal from './components/TPlotModal.vue'
import { message } from 'ant-design-vue';
import { useRoute } from 'vue-router';

const polygon = ref();
const polygons = ref<any>([])
const markers = ref<any>([]);
const amapRef = ref();
const bases = ref<any[]>([])
const baseVisible = ref(false);
const currentBase = ref(0)
const base = computed(() => bases.value[currentBase.value] || {})
const polt = ref<any>(null);
const selected = computed(() => polt.value !== null)
const allowEdit = ref(false);
const selectColor = ref(!1)
const colors = ref({
  strokeColor: '',
  fillColor: ''
})
const showPanel = ref(true)

const reflushRegion = () => {
  reflushPlot().then(_res => {
  })
}

const handleChange = (data: any) => {
  if (data.type == 'polygonEditorEnd') {
    allowEdit.value = false;
  }
}

var colorSelectedFn: Fn | undefined;
const handleOk = () => {
  colorSelectedFn?.(
    Object.fromEntries(Object.entries(toRaw(colors.value)).filter(item => item[1]))
  )
  colorSelectedFn = undefined
  selectColor.value = false;
}

const changeColor = (v: any) => {
  v.strokeColor && (colors.value.strokeColor = v.strokeColor);
  v.fillColor && (colors.value.fillColor = v.fillColor);
  const target = amapRef.value.searchOverlays((overlay: { getExtData: () => { (): any; new(): any; id: any; }; }) => overlay.getExtData().id == polt.value.id);
  target && amapRef.value.setOptions(target, v);
}

const showDetail = ref(false);
const createAction = (extData: { id: any; name?: string; bid?: any; area?: number; polygon?: { paths: AMap.LngLatLike[]; }; }, ignore: string[] = []) => {
  return [
    {
      name: '编辑', handler() {
        const target = amapRef.value.searchOverlays((overlay: { getExtData: () => { (): any; new(): any; id: any; }; }) => overlay.getExtData().id == extData.id);
        polt.value = target.getExtData();
        colors.value.strokeColor = polt.value.polygon.strokeColor
        colors.value.fillColor = polt.value.polygon.fillColor
        target && amapRef.value.editPolygon(target);
        setTimeout(() => {
          showDetail.value = true;
          allowEdit.value = true;
          showPanel.value = false;
        }, 200)
      },
    },
    {
      name: '启用/停用', handler() {
        changeStatus(extData.id).then(res => {
          if (res.success) {
            message.success('更改成功')
          }
        }).catch((e) => {
          console.log(
            e.message
          )
        })
      }
    }
  ].filter(item => !ignore.includes(item.name))
}
const rightActions = [
  {
    name: '在此处添加地块', handler(_lnglat: { lng: number; lat: number; }) {
      if (polygons.value.some((item: { extData: { id: string | string[]; }; }) => item.extData.id.includes('new'))) {
        message.error('请先保存上一个地块')
        return;
      }
      showPanel.value = false;
      message.info('点击鼠标左键开始绘制，双击左键结束绘制');
      // const paths: AMap.LngLatLike[] = [
      //   [lnglat.lng - 0.001, lnglat.lat - 0.001],
      //   [lnglat.lng - 0.001, lnglat.lat + 0.001],
      //   [lnglat.lng + 0.001, lnglat.lat + 0.001],
      //   [lnglat.lng + 0.001, lnglat.lat - 0.001],
      // ]

      const mouseTool = amapRef.value.getMousetool();
      mouseTool.on("draw", function (event: { obj: { getPath: () => any; }; }) {
        //event.obj 为绘制出来的覆盖物对象
        const paths = event.obj.getPath()
        mouseTool.close(true)
        const extData = {
          id: 'new-' + Date.now(),
          name: '新建地块',
          bid: bases.value[currentBase.value].id,
          area: AMap.GeometryUtil.ringArea(paths),
          polygon: {
            paths
          },
        }
        polygons.value = [
          ...polygons.value,
          {
            paths,
            extData,
            events: {
              onClick() {
                polt.value = extData;
                allowEdit.value = false
              },
            },
            rightActions: createAction(extData, ['启用/停用']),
            needDispatch: true
          }
        ]
      });
    }
  }
];
const getList = (bid: any) => {
  list({ bid, pageSize: 1000 }).then(res => {
    markers.value = [];
    polygons.value = res.records.map((item) => {
      const json = JSON.parse(item.polygon);
      var polygon = json ? json[0] || json : [];

      item.polygon = Object.assign({}, polygon)
      polygon.extData = item
      polygon.events = {
        onClick() {
          polt.value = item;
          allowEdit.value = false
        },
      }
      polygon.rightActions = createAction(item)

      markers.value.push({
        lnglat: getCenterPoint(item.polygon.paths), name: "<div style='font-size: 16px;line-height: 30px; text-align: center; color: #fff;'><span>" + item.name + "</span><br/><span>" + (item.area / 666.67).toFixed(2) + "</span></div>" || '', customContent: true
      })
      return polygon;
    })
    setTimeout(() => {
      if (markers.value.length == 0) {
        amapRef?.value.setCenter([base.value.longitude, base.value.latitude]);
      } else {
        amapRef?.value.setCenter(markers.value[0].lnglat)
      }
    }, 500)
  })
}

const getCenterPoint = (coordinates: string | any[]) => {
  let totalLat = 0;
  let totalLng = 0;

  for (let i = 0; i < coordinates.length; i++) {
    totalLat += coordinates[i][0];
    totalLng += coordinates[i][1];
  }

  let centerLat = totalLat / coordinates.length;
  let centerLng = totalLng / coordinates.length;

  return [centerLat, centerLng];
}
const toTarget = (extData: { id: any; }) => {
  const target = amapRef.value.searchOverlays((overlay: { getExtData: () => { (): any; new(): any; id: any; }; }) => overlay.getExtData().id == extData.id)
  target && amapRef.value.showOverlay(target)
}
const { query: { baseid } } = useRoute();
BaseList({}).then(res => {
  bases.value = res.records;
  if (!bases.value) {
    return
  }
  if (baseid) {
    res.records.map((val, index) => {
      if (val.id == baseid) {
        currentBase.value = index
      }
    });
  } else {
    res.records.map((_val, index) => {
      currentBase.value = index
    });
  }
  getList(baseid || res.records.at(-1).id)
})

watch(currentBase, (index) => {
  getList(
    bases.value[index].id
  )
})

watch(polygon, (v) => {
  if (!polt.value) {
    return
  }
  // allowEdit.value = false
  const target = v.overlays.find((overlay: { getExtData: () => { (): any; new(): any; id: any; }; }) => overlay.getExtData().id == polt.value.id);
  if (!target) {
    return
  }
  const paths = target?.getPath().map((item: { lng: any; lat: any; }) => [item.lng, item.lat]);

  polt.value.polygon = { paths }
  polt.value.polygon.fillColor = colors.value.fillColor
  polt.value.polygon.strokeColor = colors.value.strokeColor
  polt.value.area = Math.round(AMap.GeometryUtil.ringArea(paths))

})
watch(polt, (v, _o) => {
  setTimeout(() => {
    if (v == null) {
      amapRef.value.closeEditPolygon()
      getList(bases.value[currentBase.value].id)
    } else {
      colors.value.strokeColor = v.polygon.strokeColor
      colors.value.fillColor = v.polygon.fillColor
    }
  }, 200);
})

const show_djgl = () => {
  showDetail.value = !showDetail.value;
}
</script>

<style scoped>
.overflow-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;

  table-layout: fixed;
  /* adjust as needed */
}

.custom-table-layout :deep(.ant-descriptions-view table) {
  table-layout: fixed
    /* adjust as needed */
}

.sc_an {
  position: relative;
  width: 50px;
  height: 50px;
  border: 1px solid #D9D9D9;
  border-radius: 10px 0px 0px 10px;
  background: #FFFFFF;
  top: 50px;
  left: -50px;
  z-index: 99;
}

.sc_an .anicon_s {
  border-left: 3px solid #888;
  border-bottom: 3px solid #888;
  width: 20px;
  height: 20px;
  position: absolute;
  top: 15px;
  left: 12px;
  /* transform: translate(-50%, -50%); */
  transform: rotate(-135deg);
}

.dkgl_an {
  position: absolute;
  width: 50px;
  height: 50px;
  border: 1px solid #D9D9D9;
  border-radius: 10px;
  background: #FFFFFF;
  top: 50px;
  right: 0px;
  animation: move 2s infinite linear;
  cursor: pointer;
}

.dkgl_an .anicon {
  border-left: 4px solid #888;
  border-bottom: 4px solid #888;
  width: 20px;
  height: 20px;
  position: absolute;
  top: 15px;
  left: 20px;
  /* transform: translate(-50%, -50%); */
  transform: rotate(45deg);
}

.show {
  display: block;
}

.yinc {
  display: none;
}

.reflesh:hover {
  box-shadow: 5px 5px 5px #555;
}

@keyframes move {
  0% {
    transform: translateX(0);
  }

  50% {
    transform: translateX(-20px);
  }

  100% {
    transform: translateX(0);
  }
}
</style>
